const Koa = require('koa');
const path = require('path');
const logger = require('koa-morgan');
const FileStreamRotator = require('file-stream-rotator');
const koaStatic = require('koa-static');
const info = require('debug')('log:info');
const error = require('debug')('log:error');
const app = new Koa();
const config = require('../config'); 
module.exports = app;
var runing = process.env.NODE_ENV;

//访问日志
const logDirectory = path.join(__dirname,'../logs');
// fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
var accessLogStream = FileStreamRotator.getStream({
  filename: logDirectory + '/access-%DATE%.log',
  frequency: 'daily',
  verbose: false
});
app.use(logger('combined', {stream: accessLogStream}));

// 运行日志中间件
var runningLogStream = FileStreamRotator.getStream({
  filename: logDirectory + '/running-%DATE%.log',
  frequency: 'daily',
  verbose: false
});
app.use( (ctx,next)=>{
    ctx.log=(content,level='info')=>{
      let time = new Date().toLocaleString();
      let w = `[${level}][${time}]:${content}`;
      runningLogStream.write(w+'\n');
      if(level=='info'){

        info(w)
      }
      else{
        error(w)
      }
    }
    return next()
});
// 异常捕获
app.use(async (ctx,next)=>{
  try{
    // console.log(ctx.url);
    await next();
  }catch(e){
    ctx.response.status = 500;
    ctx.body = `${e}`;
    ctx.log(e,'error');
  }
})
// 静态资源
app.use(koaStatic(
  path.join( __dirname,  '../dist')
))
// 使用ctx.body解析中间件
const bodyParser = require('koa-bodyparser')
app.use(bodyParser())
// 模板、视图
// const render = require('koa-art-template');
// render(app, {
//   root: path.join(__dirname, 'views'),
//   extname: '.html',
//   debug: config[runing].debug
// });
// 路由
const router = require('./routes');
app.use(router.routes())
